package org.room402.chat.handler;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.room402.chat.process.MessageProcessManager;
import org.room402.entity.chat.MessageEvent;
import org.room402.entity.chat.UserSession;
import org.room402.framework.chat.container.ChatPoolContainer;
import org.room402.framework.chat.container.UserSessionContext;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class FastChatHandler implements WebSocketHandler {
    private final MessageProcessManager processManager;
    private final UserSessionContext userSessionContext;
    private final ChatPoolContainer chatPoolContainer;

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        return session.receive().flatMap(webSocketMessage -> {
                    String json = webSocketMessage.getPayloadAsText();
                    MessageEvent event = JSONUtil.toBean(json, MessageEvent.class);
                    return processManager.process(event, session);
                })
                .then()
                .doFinally(signalType -> {
                    System.out.println(signalType);
                    UserSession userSession = userSessionContext.removeBySid(session.getId());
                    for (String createdPoolId : userSession.getCreatedPoolIds()) {
                        chatPoolContainer.remove(createdPoolId);
                    }
                });
    }
}
